package com.always.electrical.energy.web.service;

import com.always.electrical.energy.web.data.entity.CjDydlqx;
import com.always.electrical.energy.web.data.entity.CjGlqx;
import com.always.electrical.energy.web.data.entity.EfbsCapacitorCurve;
import com.always.electrical.energy.web.data.entity.SvgCurve;
import com.always.electrical.energy.web.req.DevicesControlRunningStateReq;
import com.always.electrical.energy.web.res.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.async.DeferredResult;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * SVG、AUC、FVR
 */
@Service
public class DevicesService extends BaseService {

    // 设备查询 状态 召测
    public void controlGetRunningState(DeferredResult<WebBaseResponse> result, List<BigDecimal> deviceIds) {
        if (deviceIds.isEmpty()) {
            result.setResult(WebBaseResponse.errorDeviceIds());
        }
        Map<BigDecimal, BigDecimal> deviceIdTmlIdMap = getDeviceIdTmlIdMap(deviceIds);

        AtomicInteger countLatch = new AtomicInteger(deviceIds.size());
        DevicesControlRunningStateRes webRes = new DevicesControlRunningStateRes();

        for (BigDecimal deviceId : deviceIds) {
            DevicesControlRunningStateRes.Item webResItem = new DevicesControlRunningStateRes.Item().setId(deviceId);
            webRes.getItems().add(webResItem);
            BigDecimal tmlId = deviceIdTmlIdMap.get(deviceId);
            if (tmlId == null) {
                if (countLatch.decrementAndGet() == 0) {
                    result.setResult(WebBaseResponse.success(webRes));
                }
            } else {
                mqttClients.sendControlRunningStateGetReq(tmlId, deviceId).setCallBack((success, res) -> {
                    if (success) {
                        webResItem.setRunningState(res.getRunningState());
                    } else {
                        // todo 有真实数据之后看一下数据库的数据是不是一一对应
//                        svgCurveService.lambdaQuery().eq(SvgCurve::getMeterId, deviceId).oneOpt()
//                                .ifPresent(s -> webRes.getItems().add(webResItem.setRunningState(String.valueOf(s.getRunningState()))));
                    }
                    if (countLatch.decrementAndGet() == 0) {
                        result.setResult(WebBaseResponse.success(webRes));
                    }
                });
            }
        }
    }

    // 设备查询 模式 召测
    public void controlGetMachineMode(DeferredResult<WebBaseResponse> result, List<BigDecimal> deviceIds) {
        if (deviceIds.isEmpty()) {
            result.setResult(WebBaseResponse.errorDeviceIds());
        }
        Map<BigDecimal, BigDecimal> deviceIdTmlIdMap = getDeviceIdTmlIdMap(deviceIds);

        AtomicInteger countLatch = new AtomicInteger(deviceIds.size());
        DevicesControlMachineModeRes webRes = new DevicesControlMachineModeRes();

        for (BigDecimal deviceId : deviceIds) {
            DevicesControlMachineModeRes.Item webResItem = new DevicesControlMachineModeRes.Item().setId(deviceId);
            webRes.getItems().add(webResItem);
            BigDecimal tmlId = deviceIdTmlIdMap.get(deviceId);
            if (tmlId == null) {
                if (countLatch.decrementAndGet() == 0) {
                    result.setResult(WebBaseResponse.success(webRes));
                }
            } else {
                mqttClients.sendControlMachineModeGetReq(tmlId, deviceId).setCallBack((success, res) -> {
                    if (success) {
                        webResItem.setMachineMode(res.getMachineMode());
                    } else {
                        // todo 有真实数据之后看一下数据库的数据是不是一一对应
//                        svgCurveService.lambdaQuery().eq(SvgCurve::getMeterId, deviceId).oneOpt()
//                                .ifPresent(s -> webRes.getItems().add(webResItem.setMachineMode(String.valueOf(s.getCompMode()))));
                    }
                    if (countLatch.decrementAndGet() == 0) {
                        result.setResult(WebBaseResponse.success(webRes));
                    }
                });
            }
        }
    }

    // 设备控制 状态 设置
    public void controlSetRunningState(DeferredResult<WebBaseResponse> result, List<DevicesControlRunningStateReq.Item> items) {
        if (items.isEmpty()) {
            result.setResult(WebBaseResponse.errorDeviceIds());
        }
        Map<BigDecimal, String> deviceIdNodeIdMap = getDeviceIdNodeIdMap(
                items.stream().map(DevicesControlRunningStateReq.Item::getId).collect(Collectors.toList()));

        AtomicInteger countLatch = new AtomicInteger(items.size());
        DevicesControlRunningStateRes webRes = new DevicesControlRunningStateRes();

        for (DevicesControlRunningStateReq.Item item : items) {
            DevicesControlRunningStateRes.Item webResItem = new DevicesControlRunningStateRes.Item().setId(item.getId());
            webRes.getItems().add(webResItem);
            String nodeId = deviceIdNodeIdMap.get(item.getId());
            if (nodeId == null || nodeId.isEmpty()) {
                if (countLatch.decrementAndGet() == 0) {
                    result.setResult(WebBaseResponse.success(webRes));
                }
            } else {
                mqttClients.sendControlRunningStateSetReq(nodeId, item.getRunningState()).setCallBack((success, res) -> {
                    if (success) {
                        webResItem.setRunningState(res.getRunningState());
                    }
                    if (countLatch.decrementAndGet() == 0) {
                        result.setResult(WebBaseResponse.success(webRes));
                    }
                });
            }
        }
    }

    // 目标功率因数 查询
    public WebResponse targetPowerFactorGet(List<BigDecimal> deviceIds) {
        DevicesPowerFactorRes webRes = new DevicesPowerFactorRes();
        if (!deviceIds.isEmpty()) {
            Map<BigDecimal, BigDecimal> svgCurveMap = svgCurveService.lambdaQuery()
                    .in(SvgCurve::getMeterId, deviceIds)
                    .list()
                    .stream().collect(Collectors.toMap(SvgCurve::getMeterId, SvgCurve::getPhpfPhsa)); // todo字段没找到

            for (BigDecimal deviceId : deviceIds) {
                webRes.getItems().add(new DevicesPowerFactorRes.Item().setId(deviceId).setPowerFactor(svgCurveMap.get(deviceId)));
            }
        }
        return webRes;
    }

    // 电容器投切状态
    public DevicesCapacitorStateRes capacitorState(List<BigDecimal> deviceIds) {
        DevicesCapacitorStateRes webRes = new DevicesCapacitorStateRes();
        if (!deviceIds.isEmpty()) {
            Map<BigDecimal, EfbsCapacitorCurve> efbsCapacitorCurveMap = efbsCapacitorCurveService.selectNewList(deviceIds)
                    .stream().collect(Collectors.toMap(EfbsCapacitorCurve::getMeterId, e -> e));

            for (BigDecimal deviceId : deviceIds) {
                EfbsCapacitorCurve efbsCapacitorCurve = efbsCapacitorCurveMap.getOrDefault(deviceId, new EfbsCapacitorCurve());
                webRes.getItems().add(new DevicesCapacitorStateRes.Item().setId(deviceId)
                        .setCapacitor1PitchCutA1(efbsCapacitorCurve.getCap1Swst())
                        .setCapacitor1PitchCutB1(efbsCapacitorCurve.getCap2Swst())
                        .setCapacitor1PitchCutC1(efbsCapacitorCurve.getCap3Swst())
                        .setCapacitor1PitchCutA2(efbsCapacitorCurve.getCap4Swst())
                        .setCapacitor1PitchCutB2(efbsCapacitorCurve.getCap5Swst())
                        .setCapacitor1PitchCutC2(efbsCapacitorCurve.getCap6Swst())
                        .setCapacitor2PitchCutC1(efbsCapacitorCurve.getCap7Swst())
                        .setCapacitor2PitchCutC2(efbsCapacitorCurve.getCap8Swst())
                        .setCapacitor2PitchCutC3(efbsCapacitorCurve.getCap9Swst())
                        .setCapacitor3PitchCutC1(efbsCapacitorCurve.getCap10Swst())
                        .setCapacitor3PitchCutC2(efbsCapacitorCurve.getCap11Swst())
                        .setCapacitor3PitchCutC3(efbsCapacitorCurve.getCap12Swst())
                );
            }
        }
        return webRes;
    }

    // 显示数据数据项
    public DevicesSvgCurveDataRes svgCurveData(List<BigDecimal> deviceIds) {
        DevicesSvgCurveDataRes webRes = new DevicesSvgCurveDataRes();
        if (!deviceIds.isEmpty()) {
            Map<BigDecimal, SvgCurve> svgCurveMap = svgCurveService.selectNewList(deviceIds)
                    .stream().collect(Collectors.toMap(SvgCurve::getMeterId, e -> e));

            for (BigDecimal deviceId : deviceIds) {
                SvgCurve svgCurve = svgCurveMap.get(deviceId);
                DevicesSvgCurveDataRes.Item webResItem = new DevicesSvgCurveDataRes.Item().setId(deviceId);
                if (svgCurve != null) {
                    webResItem
                            // 功率因数 电网侧
                            .setTotPF(svgCurve.getTotpf())
                            .setPhPF_phsA(svgCurve.getPhpfPhsa())
                            .setPhPF_phsB(svgCurve.getPhpfPhsb())
                            .setPhPF_phsC(svgCurve.getPhpfPhsc())

                            // 功率因数 负载侧
                            .setLoad_TotPF(svgCurve.getLoadTotpf())
                            .setLoad_PhPF_phsA(svgCurve.getLoadPhpfPhsa())
                            .setLoad_PhPF_phsB(svgCurve.getLoadPhpfPhsb())
                            .setLoad_PhPF_phsC(svgCurve.getLoadPhpfPhsc())

                            // 无功功率 电网侧
                            .setGrid_TotVAr(svgCurve.getGridPhvarTot())
                            .setGrid_PhVAr_phsA(svgCurve.getGridPhvarA())
                            .setGrid_PhVAr_phsB(svgCurve.getGridPhvarB())
                            .setGrid_PhVAr_phsC(svgCurve.getGridPhvarC())

                            // 无功功率 负载侧
                            .setLoad_TotVAr(svgCurve.getLoadPhvarTot())
                            .setLoad_PhVAr_phsA(svgCurve.getLoadPhvarA())
                            .setLoad_PhVAr_phsB(svgCurve.getLoadPhvarB())
                            .setLoad_PhVAr_phsC(svgCurve.getLoadPhvarC())

                            // todo字段没找到
                            // THD 电流 电网侧
//                            .setGrid_THD_A_phsA(svgCurve)
//                            .setGrid_THD_A_phsB(svgCurve)
//                            .setGrid_THD_A_phsC(svgCurve)

                            // THD 电流 负载侧
//                            .setLoad_THD_A_phsA(svgCurve)
//                            .setLoad_THD_A_phsB(svgCurve)
//                            .setLoad_THD_A_phsC(svgCurve)
//                            .setLoad_THD_A_phsN(svgCurve)

                            // THD 电压 电网侧
//                            .setGrid_THD_PhV_phsA(svgCurve)
//                            .setGrid_THD_PhV_phsB(svgCurve)
//                            .setGrid_THD_PhV_phsC(svgCurve)

                            // 电流不平衡度 电网侧
                            .setGrid_A_Unbalance(svgCurve.getGridAUnbalance())
                            .setGrid_A_Negative_Unbalance(svgCurve.getGridANegativeUnbalance())
                            .setGrid_A_Zero_Unbalance(svgCurve.getGridAZeroUnbalance())

                            // 电流不平衡度 负载侧
                            .setLoad_A_Unbalance(svgCurve.getLoadAUnbalance())
                            .setLoad_A_Negative_Unbalance(svgCurve.getLoadANegativeUnbalance())
                            .setLoad_A_Zero_Unbalance(svgCurve.getLoadAZeroUnbalance())

                            // 视在功率 电网侧
                            .setGrid_TotVA(svgCurve.getGridPhvarTot())
                            .setGrid_PhVA_phsA(svgCurve.getGridPhvarA())
                            .setGrid_PhVA_phsB(svgCurve.getGridPhvarB())
                            .setGrid_PhVA_phsC(svgCurve.getGridPhvarC())

                            // 视在功率 负载侧
                            .setLoad_TotVA(svgCurve.getLoadPhvarTot())
                            .setLoad_PhVA_phsA(svgCurve.getLoadPhvarA())
                            .setLoad_PhVA_phsB(svgCurve.getLoadPhvarB())
                            .setLoad_PhVA_phsC(svgCurve.getLoadPhvarC())

                            // 电流 电网侧
                            .setGrid_A_phsA(svgCurve.getGridCurA())
                            .setGrid_A_phsB(svgCurve.getGridCurB())
                            .setGrid_A_phsC(svgCurve.getGridCurC())
//                            .setGrid_A_phsN(svgCurve)

                            // 电流 负载侧
                            .setLoad_A_phsA(svgCurve.getLoadCurA())
                            .setLoad_A_phsB(svgCurve.getLoadCurB())
                            .setLoad_A_phsC(svgCurve.getLoadCurC()
//                            .setLoad_A_phsN(svgCurve)
                    );
                } else if (deviceId.equals(new BigDecimal("2024122600000000"))) {
                    List<BigDecimal> item = svgCurveService.selectAnalogDataFvr();
                    webResItem.setGrid_THD_PhV_phsA(item.get(0))
                            .setGrid_THD_PhV_phsB(item.get(1))
                            .setGrid_THD_PhV_phsC(item.get(2));

                }
                webRes.getItems().add(webResItem);
            }
        }
        return webRes;
    }

    // 变压器 查询
    public WebResponse transformer(List<BigDecimal> deviceIds) {
        DevicesTransformerRes webRes = new DevicesTransformerRes();

        Map<BigDecimal, CjDydlqx> cjDydlqxMap = cjDydlqxService.selectNewList(deviceIds)
                .stream().collect(Collectors.toMap(CjDydlqx::getYxdnbid, e -> e));

        Map<BigDecimal, CjGlqx> cjGlqxMap = cjGlqxService.selectNewList(deviceIds)
                .stream().collect(Collectors.toMap(CjGlqx::getYxdnbid, e -> e));

        List<BigDecimal> ttus = Arrays.asList(new BigDecimal("2024103100000504"), new BigDecimal("2024103100000249"));

        if (!deviceIds.isEmpty()) {
            for (BigDecimal deviceId : deviceIds) {
                DevicesTransformerRes.Item item = new DevicesTransformerRes.Item();
                CjDydlqx cjDydlqx = cjDydlqxMap.get(deviceId);
                if (cjDydlqx != null) {
                    item.setV(cjDydlqx.getBdy());
                    if (ttus.contains(deviceId)) {
                        item.setA(cjDydlqx.getAdl() != null ? cjDydlqx.getAdl().multiply(new BigDecimal(80)) : null);
                    } else if (deviceId.equals(new BigDecimal("2024103100000626"))) {
                        item.setA(cjDydlqx.getBdl() != null ? cjDydlqx.getBdl().multiply(new BigDecimal(120)) : null);
                    } else {
                        item.setA(cjDydlqx.getBdl());
                    }
                }

                CjGlqx cjGlqx = cjGlqxMap.get(deviceId);
                if (cjGlqx != null) {
                    if (ttus.contains(deviceId)) {
                        item.setW(cjGlqx.getZyggl() != null ? cjGlqx.getZyggl().multiply(new BigDecimal(80)) : null);
                    } else if (deviceId.equals(new BigDecimal("2024103100000626"))) {
                        item.setW(cjGlqx.getZyggl() != null ? cjGlqx.getZyggl().multiply(new BigDecimal(120)) : null);
                    } else {
                        item.setW(cjGlqx.getZyggl());
                    }

                    item.setWRate(cjGlqx.getGlys());
                }
                item.setId(deviceId);
                webRes.getItems().add(item);
            }
        }
        return webRes;
    }

    // 分支箱 查询
    public WebResponse ltu(List<BigDecimal> deviceIds) {
        DevicesBranchBoxesRes webRes = new DevicesBranchBoxesRes();

        Map<BigDecimal, CjDydlqx> cjDydlqxMap = cjDydlqxService.selectNewList(deviceIds)
                .stream().collect(Collectors.toMap(CjDydlqx::getYxdnbid, e -> e));

        Map<BigDecimal, CjGlqx> cjGlqxMap = cjGlqxService.selectNewList(deviceIds)
                .stream().collect(Collectors.toMap(CjGlqx::getYxdnbid, e -> e));

        for (BigDecimal deviceId : deviceIds) {
            DevicesBranchBoxesRes.Item item = new DevicesBranchBoxesRes.Item();
            CjDydlqx cjDydlqx = cjDydlqxMap.get(deviceId);
            if (cjDydlqx != null) {
                BeanUtils.copyProperties(cjDydlqx, item);
            }

            CjGlqx cjGlqx = cjGlqxMap.get(deviceId);
            if (cjGlqx != null) {
                BeanUtils.copyProperties(cjGlqx, item);
            }
            item.setId(deviceId);
            webRes.getItems().add(item);
        }
        return webRes;
    }



    // 通电状态 查询
    public DeviceSvgCurveRsRes svgCurveRunningState(List<BigDecimal> deviceIds) {
        DeviceSvgCurveRsRes webRes = new DeviceSvgCurveRsRes();
        if (!deviceIds.isEmpty()) {
            Map<BigDecimal, SvgCurve> svgCurveMap = svgCurveService.selectNewList(deviceIds)
                    .stream().collect(Collectors.toMap(SvgCurve::getMeterId, e -> e));

            for (BigDecimal deviceId : deviceIds) {
                SvgCurve svgCurve = svgCurveMap.get(deviceId);
                DeviceSvgCurveRsRes.Item webResItem = new DeviceSvgCurveRsRes.Item().setId(deviceId);;
                if (svgCurve != null) {
                    webResItem.setRunningState(svgCurve.getRunningState());
                }
                webRes.getItems().add(webResItem);
            }
        }
        return webRes;
    }

}
